# -*- coding:UTF-8 -*-
import crossplane
import os
import sys

# 将整个项目加入解析器的搜索目录
# sys.path.append(os.getcwd())
from utils.common import setup_log

logger = setup_log("nginx_mgmt.log")


def operate_nginx(mode, nginx_name, server_name, ip, port):
    """
    配置nginx vhost 检查并重载
    """
    if ip is None:
        logger.error("nginx: ip is None")
        return False

    nginx_data = ""
    file_dir = f'/etc/nginx/vhost/{nginx_name}.conf'
    if mode == "del":
        if os.path.exists(file_dir):
            os.remove(file_dir)
            os.system("nginx -s reload")
            logger.info(f"nginx: del {file_dir} ok and reload successfully")
        return True
    elif mode == "new":
        with open("./template/template_nginx.conf", 'r', encoding='utf8') as f:
            nginx_data = f.read()
        nginx_data = nginx_data.replace("!server_name!", server_name)
        nginx_data = nginx_data.replace("!ip!", str(ip))
        nginx_data = nginx_data.replace("!port!", str(port))
        with open(f"./vhost/{nginx_name}.conf", 'w', encoding='utf-8') as f:
            f.write(nginx_data)
    # 校验config文件合法性 nginx -t
    payload = crossplane.parse(f"./vhost/{nginx_name}.conf")
    # payload = crossplane.lex(f"./vhost/{nginx_name}.conf")
    status = payload['status']
    # nginx 配置文件检查无异常
    if status == "ok":
        # print("----nginx文件检查成功-----")
        with open(file_dir, 'w', encoding='utf-8') as f:
            nginx_data = nginx_data.replace("http{", "")
            nginx_data_end = nginx_data.rfind("}")
            nginx_data = nginx_data[:nginx_data_end]
            f.write(nginx_data)
        # 重启nginx：
        # 进入nginx可执行目录sbin下，输入命令./nginx -s reload 即可
        os.system("nginx -s reload")
        logger.info(f"nginx: new {file_dir} ok and reload successfully")
        return True
    os.system("nginx -s reload")
    logger.error(f"nginx: crossplane ./vhost/{nginx_name}.conf is error")
    return False
